package com.example.demo.service.impl;

import com.example.demo.admin.dto.SearchFiles;
import com.example.demo.admin.pojo.Files;
import com.example.demo.admin.pojo.PageResult;
import com.example.demo.mapper.UploadMapper;
import com.example.demo.service.UploadService;
import com.example.demo.utils.AliOssUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UploadMapper uploadMapper;
    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public String addfile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String objectName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
        String filePath = null;
        try {
            filePath = AliOssUtil.upload(file.getBytes(), objectName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long size = (long) Math.ceil((double) file.getSize() /1024);
        Files files = Files.builder()
                .fileName(filename)
                .fileSize(size)
                .url(filePath)
                .createTime(LocalDateTime.now())
                .build();
        uploadMapper.addFile(files);

        return filePath;
    }

    /**
     * 查找文件
     * @return
     */
    @Override
    public PageResult list(SearchFiles searchFiles) {
        PageHelper.startPage(searchFiles.getCurrentPage(), searchFiles.getPageSize());
        Page<Files> page =  uploadMapper.list(searchFiles.getFileName());
        return PageResult.builder()
                .total(page.getTotal())
                .records(page.getResult())
                .build();
    }

    /**
     * 删除文件
     * @param url
     */
    @Override
    public void deleteFiles(String url) {
        String objectName = url.substring(url.lastIndexOf("/")+1);
        uploadMapper.deleteFiles(url);
        AliOssUtil.deleteFile(objectName);
    }
}
